import { View } from "@tarojs/components"
import Taro from "@tarojs/taro"
import { observer } from "mobx-react"
import { useEffect, useState } from "react"
import { InfoBtn } from "src/components/info-btn"
import { UserInfoCard } from "src/components/info-card"
import { infoStore } from "src/store/info"
import { AtButton, AtMessage } from "taro-ui"

const Mine = observer(() => {
  const [userInfo, setUserInfo] = useState<{avatar: string, nickName: string}>();
  const { setUserInfo: updateStore } = infoStore;

  useEffect(() => {
    if (userInfo) {
      Taro.setStorage({key: 'userInfo', data: userInfo});
    } else {
      Taro.removeStorage({key: 'userInfo'})
    }
    updateStore(userInfo);
  }, [userInfo])

  useEffect(() => {
    Taro.getStorage({key: 'userInfo'}).then(res => {
      if (res) {
        setUserInfo(res.data);
      }
    }).catch(() => {
      //
    });
  }, []);


  return (
    <View style={{ padding: "20px" }}>
      <AtMessage />
      <UserInfoCard {...userInfo} />
      {!userInfo?.avatar && <InfoBtn setUserInfo={setUserInfo} />}
      {userInfo?.avatar && <AtButton type="primary" onClick={() => setUserInfo(undefined)}>退出登录</AtButton>}
    </View>
  )
})

export default Mine;
